function groupGrid()
{
    $('#groupGrid').jqGrid({
                url: siteUrl + 'group/get_groups',
                mtype: 'post',
                datatype: 'json',
                colNames: ['ID','Group name', 'Group Password' ,'Operations'],
                colModel: [
                {name: 'user_id', index: 'user_id', hidden: true, key: true},
                {name: 'group_name', index: 'group_name'},
                {name: 'password', index: 'password'},
                {name: 'ops', index: 'ops', align: 'center', sortable: false, formatter: groupOperations}
                ],


            autowidth: true,
            height: '200',
            pager: $('#pagination'),
            sortname: 'group_id',
            sortorder: 'asc',
            viewrecords: true,
            rownumbers: true,
            ondblClickRow: function(rowId, iRow, iCol, e) {
                window.location = siteUrl + 'group/view/' + rowId;
            }
    });
}
function groupStudentGrid()
{
    $('#groupStudentGrid').jqGrid({
                url: siteUrl + 'group/get_student_groups',
                mtype: 'post',
                datatype: 'json',
                colNames: ['ID','Class name','Instructor', 'student_id', 'Operations'],
                colModel: [
                {name: 'group_id', index: 'group_id', hidden: true, key: true},
                {name: 'group_name', index: 'group_name'},
                {name: 'insturctor', index: 'instructor'},
                {name: 'student_id', index: 'student_id', hidden: true},
                {name: 'ops', index: 'ops', align: 'center', sortable: false, formatter: groupStudentOperations}
                ],
            autowidth: true,
            height: '200',
            pager: $('#pagination'),
            sortname: 'group_id',
            sortorder: 'asc',
            viewrecords: true,
            rownumbers: true,
            ondblClickRow: function(rowId, iRow, iCol, e) {
                
            }
    });
}


function groupInstructorGrid()
{
    $('#groupInstructorGrid').jqGrid({
                url: siteUrl + 'group/get_instructor_groups',
                mtype: 'post',
                datatype: 'json',
                colNames: ['ID','Class name','Password', 'Operations'],
                colModel: [
                {name: 'group_id', index: 'group_id', hidden: true, key: true},
                {name: 'group_name', index: 'group_name'},
                {name: 'password', index: 'password'},
                {name: 'ops', index: 'ops', align: 'center', sortable: false, formatter: groupInstructorOperations}
                ],
            autowidth: true,
            height: '200',
            pager: $('#pagination'),
            sortname: 'group_id',
            sortorder: 'asc',
            viewrecords: true,
            rownumbers: true,
    });
}

function groupMembersGrid()
{
    $('#groupMembersGrid').jqGrid({
            url: siteUrl + 'group/get_group_members',
            mtype: 'post',
            postData: {
              'group_id': $('#group_id').val()
            },
            datatype: 'json',
            colNames: ['ID','Fullname',],
            colModel: [
                {name: 'users_groups_id', index: 'users_groups_id', hidden: true, key: true},
                {name: 'fullname', index: 'fullname'},
            ],
            autowidth: true,
            height: '200',
            pager: $('#pagination'),
            sortname: 'users_groups_id',
            sortorder: 'asc',
            viewrecords: true,
            rownumbers: true
    });
}

function groupOperations(cell, opts, rowObj)
{
    var id = opts.rowId;
    
    var edit = '<a href="' + siteUrl + 'group/edit/' + id + '" title="Update" class="icon icon-update"></a>';

    var del = '<a href="javascript:$.confirmDelete(' + id + ', \'deleteGroup\', \'Group - Delete Record\')" title="Delete" class="icon icon-delete"></a>';

    
    return edit+del;
}
function groupStudentOperations(cell, opts, rowObj)
{
    var id = opts.rowId;

    var enter = '<a href="' + siteUrl + 'group/enter/' + id + '" title="Enter" class="icon24 icon-door"></a>';

    return enter;
}
function groupInstructorOperations(cell, opts, rowObj)
{
    var id = opts.rowId;

    var enter = '<a href="' + siteUrl + 'group/enter_instructor/' + id + '" title="Enter" class="icon24 icon-door"></a>';

    return enter;
}

function groupRules()
{
    


    $('#group_form').validate({
        debug: true,
        rules: {

           group_name:{
                required: true,
                remote: {
                    url: siteUrl + 'group/unique',
                    type: 'get',
                    data: {
                        field: 'group_name',
                        group_id: function() {
                            return $('#group_id').val();
                        }
                    }
                }
            },
            group_password: 'required'

        },
        messages: {
            group_name:  'Group name must be unique'

        },
        onkeyup: false,
        focusInvalid: true,
        errorElement: 'span',
        errorPlacement: function(error, element) {
            $(element).next('.icon-error').remove();
            $(element).parent().append('<span class="icon icon-error"></span>');
            var icon = $(element).next('span');

            icon.qtip({
                content: $(error).text(),
                position: {
                    corner: {
                        target: 'rightTop',
                        tooltip: 'leftBottom'
                    }
                },
                hide: {
                    when: 'inactive',
                    delay: 1500
                },
                style: 'fielderror'
            });
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('ui-state-error ui-corner-all');
        },
        unhighlight: function(element, errorClass) {
            $(element).next('.icon-error').remove();
            $(element).parent().removeClass('ui-state-error ui-corner-all');
        },
        submitHandler: function(form) {
            saveGroup();
        }
    });

}

function saveGroup(){
    $.loading('Group - Adding Group');
    
    $.ajax({
        url: siteUrl + 'group/submit',
        type: 'post',
        data: $('#group_form').serialize(),
        success: function(response) {
            
            if (response)
            {
                window.location = siteUrl + 'group';
            }
        }
    });
}

function groupSettingRules()
{
    $('#group_form').validate({
        debug: true,
        rules: {
            group_password: 'required'
        },
        messages: {
            group_password: $.Msgs('required')
        },
        onkeyup: false,
        focusInvalid: true,
        errorElement: 'span',
        errorPlacement: function(error, element) {
            $(element).next('.icon-error').remove();
            $(element).parent().append('<span class="icon icon-error"></span>');
            var icon = $(element).next('span');

            icon.qtip({
                content: $(error).text(),
                position: {
                    corner: {
                        target: 'rightTop',
                        tooltip: 'leftBottom'
                    }
                },
                hide: {
                    when: 'inactive',
                    delay: 1500
                },
                style: 'fielderror'
            });
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('ui-state-error ui-corner-all');
        },
        unhighlight: function(element, errorClass) {
            $(element).next('.icon-error').remove();
            $(element).parent().removeClass('ui-state-error ui-corner-all');
        },
        submitHandler: function(form) {
            saveGroupSetting();
        }
    });

}

function saveGroupSetting(){
    $.loading('Group - Saving');
    
    $.ajax({
        url: siteUrl + 'group/save_group_setting',
        type: 'post',
        data: $('#group_form').serialize(),
        success: function(response) {
            if (response)
            {
                window.location = siteUrl + 'group/enter_instructor/'+ $('#group_id').val();
            }
        }
    });
}

function join_group_dialog() {
   $('#join_group_div').attr('title', 'Join class');
   $('#join_group_div').dialog({
            resizable: false,
            height: '300',
            width: 'auto',
            modal: true,
            buttons: {
                    'Cancel': function() {
                            window.location = siteUrl + 'group/student_list';
                            //$(this).dialog('close');
                    },
                    'Join': function() {
                        join_group();
                    }
            },
            close: function() {
                    window.location = siteUrl + 'group/student_list';
                    $(this).dialog('destroy');

            }
    }).removeClass('hidden');
}

function join_group()
{
	$.ajax({
		url: siteUrl + 'group/check_group',
		type: 'post',
		data: $('#join_group_form').serialize(),
		dataType: 'json',
		beforeSend: function() {
			if ($('#password').val() == '')
			{
				$('#err').children('.msg').html('Password is required.');
				$('#err').fadeIn('normal');
				return false;
			}
		},
		success: function(response) {

			if (response == true)
			{
				window.location = siteUrl + 'group/enter/'+$('#group_id').val();
			}
			else
			{
				$('#err').children('.msg').html('Invalid password.');
				$('#err').fadeIn('normal');
			}
		}
	});
}

function deleteGroup(groupId)
{
    $.loading('Group - Deleting Record');

    $.ajax({
        url: siteUrl + 'group/delete/' + groupId,
        type: 'post',
        dataType: 'json',
        success: function(response) {
            if (response == true)
            {
                window.location = siteUrl + 'group';
            }

        }
    });
}

function filterItems(){
    $('#groupGrid').setGridParam({
    postData:
        {
            group_name: $('#group_name').val()
        }
}).trigger('reloadGrid');
}

function filterStudentGroup(){

    $('#groupStudentGrid').setGridParam({
    postData:
        {
            search: $('#search').val()
        }
    }).trigger('reloadGrid');
}

function filterGroupMember() {
    $('#groupMembersGrid').setGridParam({
    postData:
        {
            search: $('#search').val()
        }
    }).trigger('reloadGrid');
}